<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="模型标识" prop="modelKey">
        <el-input
          v-model="queryParams.modelKey"
          placeholder="请输入模型标识"
          clearable
          @keyup="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程分类" prop="category">
        <el-select
          v-model="queryParams.category"
          clearable
          placeholder="请选择流程分类"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- v-hasPermi="['workflow:model:add']" -->
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['workflow:model:remove']" -->
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['workflow:model:export']" -->
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      fit
      :data="modelList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="模型标识"
        prop="modelKey"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="模型名称" :show-overflow-tooltip="true">
        <template #default="scope">
          <span
            class="text-#1890ff pointer"
            @click="handleProcessView(scope.row)"
            >{{ scope.row.modelName }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="流程分类"
        prop="categoryName"
        :formatter="categoryFormat"
      />
      <el-table-column label="模型版本">
        <template #default="scope">
          <el-tag>v{{ scope.row.version }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="描述"
        prop="description"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="创建时间" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
        width="300"
      >
        <template #default="scope">
          <!-- v-hasPermi="['workflow:model:edit']" -->
          <el-button
            class="text-#1890ff p-0"
            icon="el-icon-edit"
            type="primary"
            text
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <!-- v-hasPermi="['workflow:model:designer']" -->
          <el-button
            class="text-#1890ff p-0"
            icon="el-icon-brush"
            type="primary"
            text
            @click="handleDesigner(scope.row)"
            >设计</el-button
          >
          <!-- v-hasPermi="['workflow:model:deploy']" -->
          <el-button
            class="text-#1890ff p-0"
            icon="el-icon-video-play"
            type="primary"
            text
            @click="handleDeploy(scope.row)"
            >部署</el-button
          >
          <!-- v-hasPermi="[
              'workflow:model:query',
              'workflow:model:list',
              'workflow:model:remove'
            ]" -->
          <el-dropdown>
            <el-button text icon="el-icon-d-arrow-right" class="p-0 ml-10px"
              >更多</el-button
            >
            <template #dropdown>
              <el-dropdown-menu>
                <!-- <div v-hasPermi="['workflow:model:query']"> -->
                <el-dropdown-item
                  icon="el-icon-view"
                  @click="handleProcessView(scope.row)"
                  >流程图</el-dropdown-item
                >
                <!-- </div> -->
                <!-- <div v-hasPermi="['workflow:model:list']"> -->
                <el-dropdown-item
                  icon="el-icon-price-tag"
                  @click="handleHistory(scope.row)"
                  >历史</el-dropdown-item
                >
                <!-- </div> -->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!--  添加或修改模型信息对话框  -->
    <el-dialog
      :title="title"
      v-model="open"
      width="30%"
      append-to-body
      @close="cancel()"
    >
      <el-form ref="form" :model="formModel" :rules="rules" label-width="100px">
        <el-form-item label="模型标识" prop="modelKey">
          <el-input v-model="formModel.modelKey" clearable disabled />
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName">
          <el-input
            v-model="formModel.modelName"
            clearable
            :disabled="formModel.modelId !== undefined"
          />
        </el-form-item>
        <el-form-item label="流程分类" prop="category">
          <el-select
            v-model="formModel.category"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属单位：" prop="orgIds">
          <el-tree-select
            ref="companyIdRef"
            style="width: 100%"
            clearable
            show-checkbox
            multiple
            :check-strictly="true"
            v-model="formModel.orgIds"
            :data="companyOptions"
            :check-on-click-node="true"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            placeholder="请选择归属单位"
            value-key="id"
            filterable
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formModel.description"
            type="textarea"
            placeholder="请输入内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="footer text-right">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 流程图 -->
    <el-dialog
      :title="processView.title"
      v-model="processView.open"
      width="70%"
      append-to-body
      height="40%"
    >
      <my-process-viewer
        key="designer"
        :value="processView.xmlData"
        v-bind="bpmnControlForm"
        :prefix="bpmnControlForm.prefix"
        :activityData="activityList"
        :processInstanceData="processInstance"
        :taskData="tasks"
      />
    </el-dialog>

    <el-dialog title="模型历史" v-model="history.open" width="80%">
      <el-table
        v-loading="history.loading"
        fit
        :data="historyList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="模型标识"
          prop="modelKey"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="模型名称" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-button text @click="handleProcessView(scope.row)">
              <span>{{ scope.row.modelName }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="流程分类"
          prop="categoryName"
          :formatter="categoryFormat"
        />
        <el-table-column label="模型版本" width="80">
          <template #default="scope">
            <el-tag size="small">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="描述"
          prop="description"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="300"
          class-name="small-padding"
        >
          <template #default="scope">
            <!-- v-hasPermi="['workflow:model:deploy']" -->
            <el-button type="primary" text @click="handleDeploy(scope.row)"
              >部署</el-button
            >
            <!-- v-hasPermi="['workflow:model:save']" -->
            <el-button type="primary" text @click="handleLatest(scope.row)"
              >设为最新</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="historyTotal > 0"
        :total="historyTotal"
        v-model:page="queryHistoryParams.pageNum"
        v-model:limit="queryHistoryParams.pageSize"
        @pagination="getHistoryList"
      />
    </el-dialog>
  </div>
</template>

<script name="WorkModel" setup>
import { useRoute, useRouter } from 'vue-router'
import {
  getBpmnXml,
  listModel,
  historyModel,
  latestModel,
  addModel,
  updateModel,
  saveModel,
  delModel,
  deployModel
} from '@/api/workflow/model'
import { companyOptions } from '@/hooks/dict/useProject'
import { listCategory } from '@/api/workflow/category'
import myProcessViewer from '@/components/bpmnProcessDesigner/package/designer/ProcessViewer.vue'
import ModelEditor from './modelEditor'
import { getToken } from '@/utils/auth'
import { toRefs } from 'vue'
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const data = reactive({
  // 遮罩层
  loading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 流程模型表格数据
  modelList: [],
  categoryOptions: [],
  title: '',
  open: false,
  formModel: {},
  // 表单校验
  rules: {
    modelKey: [
      { required: true, message: '模型标识不能为空', trigger: 'blur' }
    ],
    modelName: [
      { required: true, message: '模型名称不能为空', trigger: 'blur' }
    ],
    category: [{ required: true, message: '请选择类型', trigger: 'change' }],
    orgIds: [{ required: true, message: '请选择归属单位', trigger: 'change' }]
  },
  designerOpen: false,
  designerData: {
    loading: false,
    bpmnXml: '',
    modelId: null,
    form: {
      processName: null,
      processKey: null
    }
  },
  designerModelId: null,
  processView: {
    title: '',
    open: false,
    index: undefined,
    xmlData: ''
  },
  // bpmn.xml 导入
  upload: {
    // 是否显示弹出层（xml导入）
    open: false,
    // 弹出层标题（xml导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    name: null,
    category: null,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() }
    // 上传的地址
    // url: process.env.VUE_APP_BASE_API + '/workflow/definition/import'
  },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelKey: null,
    modelName: null,
    category: null
  },
  currentRow: null,
  history: {
    open: false,
    loading: false
  },
  historyList: [],
  historyTotal: 0,
  queryHistoryParams: {
    pageNum: 1,
    pageSize: 10,
    modelKey: null
  }
})
const {
  categoryOptions,
  loading,
  ids,
  single,
  multiple,
  showSearch,
  total,
  modelList,
  title,
  open,
  formModel,
  rules,
  designerOpen,
  designerData,
  designerModelId,
  processView,
  upload,
  queryParams,
  currentRow,
  history,
  historyList,
  historyTotal,
  queryHistoryParams
} = toRefs(data)
/** 查询流程分类列表 */
const getCategoryList = () => {
  listCategory().then(response => (categoryOptions.value = response.rows))
}
/** 查询流程模型列表 */
const getList = () => {
  loading.value = true
  listModel(queryParams.value).then(response => {
    modelList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
const cancel = () => {
  reset()
  // 关闭dialog
  open.value = false
}
// 表单重置
const reset = () => {
  formModel.value = {
    modelId: undefined,
    modelKey: undefined,
    modelName: undefined,
    category: undefined,
    description: undefined
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm('queryForm')
  handleQuery()
}
// 多选框选中数据
const handleSelectionChange = selection => {
  ids.value = selection.map(item => item.modelId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
/** 部署流程 */
const handleDeploy = row => {
  loading.value = true
  deployModel({
    modelId: row.modelId
  })
    .then(response => {
      proxy.$modal.msgSuccess('部署成功')
    })
    .finally(() => {
      loading.value = false
    })
}
// ========== 高亮流程图 start ==========
const bpmnControlForm = ref({
  prefix: 'flowable'
})
const activityList = ref([])
const processInstance = ref({})
const tasks = ref([])
/** 查看流程图 */
const handleProcessView = row => {
  let modelId = row.modelId
  processView.value.title = '流程图'
  processView.value.index = modelId
  // 发送请求，获取xml
  getBpmnXml(modelId).then(response => {
    processView.value.xmlData = response.data
  })
  processView.value.open = true
}
// ========== 高亮流程图 end ==========
const getHistoryList = () => {
  history.value.loading = true
  historyModel(queryHistoryParams.value).then(response => {
    historyTotal.value = response.total
    historyList.value = response.rows
    history.value.loading = false
  })
}
const handleHistory = row => {
  history.value.open = true
  queryHistoryParams.value.modelKey = row.modelKey
  getHistoryList()
}
/** 设为最新版 */
const handleLatest = row => {
  proxy.$modal.confirm('是否确认将此版本设为最新？').then(() => {
    history.value.loading = true
    latestModel({
      modelId: row.modelId
    })
      .then(response => {
        history.value.open = false
        getList()
        proxy.$modal.msgSuccess('操作成功')
      })
      .finally(() => {
        history.value.loading = false
      })
  })
}
const handleCurrentChange = data => {
  if (data) {
    currentRow.value = JSON.parse(data.content)
  }
}
/** 新增流程模型 */
const handleAdd = () => {
  title.value = '新增流程模型'
  const dateTime = new Date().getTime()
  formModel.value = {
    modelKey: `Process_${dateTime}`,
    modelName: `业务流程_${dateTime}`
  }
  open.value = true
}
/** 修改按钮操作 */
const handleUpdate = row => {
  title.value = '修改流程模型'
  formModel.value = {
    modelId: row.modelId,
    modelKey: row.modelKey,
    modelName: row.modelName,
    category: row.category,
    orgIds: row.orgIds ? row.orgIds.split(',').map(Number) : null,
    description: row.description
  }
  open.value = true
}
const submitForm = () => {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      let prams = JSON.parse(JSON.stringify(formModel.value))
      prams.orgIds = formModel.value.orgIds
        ? formModel.value.orgIds.toString()
        : ''
      if (formModel.value.modelId !== undefined) {
        updateModel(prams).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addModel(prams).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 设计按钮操作 */
const handleDesigner = row => {
  // 设计流程
  router.push({
    path: '/process/modelEditors',
    query: { modelId: row.modelId.toString() }
  })
}
const confirmSave = (body, newVersion) => {
  designerData.value.loading = true
  saveModel(
    Object.assign(body, {
      newVersion: newVersion
    })
  )
    .then(() => {
      designerOpen.value = false
      getList()
    })
    .finally(() => {
      designerData.value.loading = false
    })
}
/** 删除按钮操作 */
const handleDelete = row => {
  const modelIds = row.modelId || ids.value
  proxy.$modal
    .confirm('是否确认删除该数据项？')
    .then(() => {
      loading.value = true
      return delModel(modelIds)
    })
    .then(() => {
      loading.value = false
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .finally(() => {
      loading.value = false
    })
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy.downLoadByUrl(
    'bpmn/workflow/model/export',
    {
      ...queryParams.value
    },
    `wf_model_${new Date().getTime()}.xlsx`
  )
}
/** 导入bpmn.xml文件 */
const handleImport = () => {
  upload.value.title = 'bpmn20.xml文件导入'
  upload.value.open = true
}
// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
  upload.value.isUploading = true
}
// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {
  upload.value.open = false
  upload.value.isUploading = false
  proxy.$refs.upload.clearFiles()
  proxy.$message.success(response.msg)
  getList()
}
// 提交上传文件
const submitFileForm = () => {
  proxy.$refs.uploadForm.validate(valid => {
    if (valid) {
      proxy.$refs.upload.submit()
    }
  })
}
const categoryFormat = (row, column) => {
  return (
    categoryOptions.value.find(k => k.code === row.category)?.categoryName ?? ''
  )
}
const submitSave = () => {
  getList()
}
watch(
  () => route,
  (newVal, oldVal) => {
    if (location.href.match(/workModel/)) {
      getList()
    }
  },
  {
    deep: true
  }
)
getCategoryList()
getList()
</script>
